

#include "Controls.h"
#include "SDL/SDL.h"
#include "SDLview.h"
#include "Camera.h"


SDL_Event event;

Controls* Controls::_instance = NULL;

Controls* Controls::Instance()
{
	if (_instance == NULL)
	{
		_instance = new Controls;
	}
	return _instance;
}

Controls::Controls() {}

UserAction Controls::checkUserInput(Camera* camera)
{		
	enum UserAction action;

	SDL_PumpEvents();
	
	action = NOACTION;
			
	while ( SDL_PollEvent (&event) ) 
	{
		switch (event.type) {			
			
			case SDL_MOUSEMOTION:
				Look(camera);
				return action;
				break;
				
			case SDL_MOUSEBUTTONDOWN:
				//leftbutton = DOWN;
				break;
				
			case SDL_MOUSEBUTTONUP:
				//leftbutton = UP;
				break;
				
			case SDL_KEYDOWN:	
				
				switch( event.key.keysym.sym )
				{
					case SDLK_ESCAPE:
						action = QUIT;
						return action;
						break;
						
					case SDLK_a:
						camera->goLeft();
						break;	
						
					case SDLK_d:
						camera->goRight();
						break;	
						
					case SDLK_w:
						camera->goForward();
						break;	
						
					case SDLK_s:
						camera->goBackward();
						break;	
						
					case SDLK_SPACE:
						action = STEP;
						return action;
						break;
						
					default:
						break;
				}
				
			default:
			break;
		}
	}	
	
	return action;
}


void Controls::Look(Camera *camera)
{
	int mouse_dx, mouse_dy;
	
	int MAX_MOUSE_MOTION = 40;
	
	(Uint8)SDL_GetRelativeMouseState(&mouse_dx, &mouse_dy);	
	
	if (mouse_dx>MAX_MOUSE_MOTION)
		mouse_dx = MAX_MOUSE_MOTION;
	else if (mouse_dx<-MAX_MOUSE_MOTION) 
		mouse_dx = -MAX_MOUSE_MOTION;
	
	if (mouse_dy>MAX_MOUSE_MOTION) 
		mouse_dy = MAX_MOUSE_MOTION;
	else if (mouse_dy<-MAX_MOUSE_MOTION) 
		mouse_dy = -MAX_MOUSE_MOTION;
	
	float dAngle   = 1.5e-3f * 2.0*M_PI*(float)mouse_dx;	
	float dAzimuth = -1.5e-3f * 2.0*M_PI*(float)mouse_dy;	
	
	camera->RotateViewAboutVertical(dAngle);
	camera->RotateViewAboutHorizontal(dAzimuth);
	
	int dims[2];
	SDLview::Instance()->getViewDims(dims);

}




